package utils;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

import javax.sql.DataSource;

import com.alibaba.druid.pool.DruidDataSourceFactory;

public class JdbcUtils {
	
	private static ThreadLocal<Connection> pool=new ThreadLocal<Connection>();
	private static DataSource dataSource=null;
	private static Properties p=null;
	static {
		InputStream in = JdbcUtils.class.getClassLoader().getResourceAsStream("db2.properties");
		p=new Properties();
		try {
			p.load(in);
			dataSource = DruidDataSourceFactory.createDataSource(p);
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}		
		
	}
	
	public static Connection getConnection() throws SQLException {
		Connection connection = pool.get();
		if(connection==null) {
			
				pool.set(dataSource.getConnection());
			
		}
		return pool.get();
	}
	
	public static void close() {
		Connection connection = pool.get();
		if(connection!=null) {
			try {
				connection.close();
				pool.remove();
			} catch (SQLException e) {
				e.printStackTrace();
			}
			
		}
		
	}
	

}
